
SeuratStackCountPlot <- function(seurat.object,
                                 group.by,
                                 stack.by,
                                 percentage = FALSE,

                                 xlab = "",
                                 x.axis.angle = 45,
                                 ylab = "",
                                 title = NULL,
                                 legend.title = NULL,
                                 cols = NULL,
                                 save.table = FALSE,
                                 save.plot = FALSE,
                                 ...) {


                                    
  if (percentage) {
    group.table <- seurat.object@meta.data %>% 
      dplyr::count(!! sym(group.by))
    rownames(group.table) <- group.table[[group.by]]
    plot.table <- seurat.object@meta.data %>% 
      dplyr::count(!! sym(group.by), !! sym(stack.by)) %>% 
      dplyr::mutate(value = n / group.table[!! sym(group.by), "n"])
  }
  else
    plot.table <- seurat.object@meta.data %>%
      dplyr::count(!! sym(group.by), !! sym(stack.by)) %>%
      dplyr::mutate(value = n)
  if (save.table)
    write.csv(plot.table, file = "plot.table.csv")
  plot <- plot.table %>%
    ggplot(aes(x = !!sym(group.by), y = value, fill = !!sym(stack.by))) +
    geom_bar(stat = "identity", position = "stack", width = 0.8) +
    cowplot::theme_cowplot() +
    theme(axis.text.x = element_text(angle = x.axis.angle, hjust = 0.5, vjust = 0.5)) +
    ggtitle("") +
    xlab("") +
    ylab("")
  if (percentage)
    plot <- plot + scale_y_continuous(labels = scales::percent)
  if (! is.null(legend.title))
    plot <- plot +
    guides(fill = guide_legend(title = labs(title = legend.title)))
  else
    plot <- plot +
    guides(fill = guide_legend(title = NULL))
  # theme(axis.ticks.length = unit(0.5, 'cm'))
  if (! is.null(title))
    plot <- plot +
    ggtitle(title) +
    theme(plot.title = element_text(hjust = 0.5))
  if (! is.null(cols))
    plot <- plot +
    scale_color_manual(values = cols) +
    scale_fill_manual(values = cols)
  if (save.plot) {
    plot
    SaveImage(...)
  }
  else
    return(plot)
}